<template>
  <div class="bg-amber-400 h-[50px] space-x-4 flex items-center px-4">
    <template v-for="(app, index) in apps" :key="index">
      <a-button
        @contextmenu="onContextmenu"
        :type="activeApp.id === app.id ? 'primary' : undefined"
        @click="changeApp(app)"
      >
        {{ app.name }}
        <RedoOutlined @click.stop="reload(app)" />
        <QuestionOutlined @click.stop="openDevtools(app)" />
        <CloseOutlined @click.stop="remoteAppTag(app, index)" />
      </a-button>
    </template>
  </div>
</template>

<script setup>
  import { ref, onMounted, watchEffect } from 'vue';
  import { ipcRenderer } from 'electron';
  import { RedoOutlined, QuestionOutlined, CloseOutlined } from '@ant-design/icons-vue';
  import { Modal } from 'ant-design-vue';

  const sessionStoreKeyPrefix = 'workbenchApplicationWindow';

  const apps = ref(
    (() => {
      const storeData = sessionStorage.getItem(`${sessionStoreKeyPrefix}__apps`);
      if (storeData) {
        return JSON.parse(storeData);
      }
      return [];
    })(),
  );
  const activeApp = ref(
    (() => {
      const storeData = sessionStorage.getItem(`${sessionStoreKeyPrefix}__activeApp`);
      if (storeData) {
        return JSON.parse(storeData);
      }
      return {};
    })(),
  );

  watchEffect(() => {
    sessionStorage.setItem(`${sessionStoreKeyPrefix}__apps`, JSON.stringify(apps.value));
    sessionStorage.setItem(`${sessionStoreKeyPrefix}__activeApp`, JSON.stringify(activeApp.value));
  });

  onMounted(() => {
    ipcRenderer.on(
      'sendRenderer__workbenchApplicationWindow_openAppInfo',
      handleMainMessageOpenAppInfo,
    );

    ipcRenderer.on('sendRenderer__workbenchApplicationWindow_shouldCloseWindow', shouldCloseWindow);
  });

  function handleMainMessageOpenAppInfo(event, params) {
    const appInfo = params.data.appInfo;
    const openedApp = apps.value.find(v => v.id === appInfo.id);
    if (!openedApp) {
      apps.value.push(appInfo);
    }
    activeApp.value = appInfo;
  }

  function changeApp(appInfo) {
    if (appInfo.id === activeApp.value.id) {
      return;
    }
    activeApp.value = appInfo;
    ipcRenderer.send('sendMain__workbenchApplicationWindow_changeApp', appInfo.id);
  }

  function reload(appInfo) {
    ipcRenderer.send('sendMain__workbenchApplicationWindow_reloadApp', appInfo.id);
  }

  function openDevtools(appInfo) {
    ipcRenderer.send('sendMain__workbenchApplicationWindow_openDevtools', appInfo.id);
  }

  function remoteApp(appInfo) {
    return ipcRenderer.invoke('sendMain__workbenchApplicationWindow_remoteApp', appInfo.id);
  }

  function remoteAppTag(appInfo, index) {
    if (appInfo.id !== activeApp.value.id) {
      remoteApp(appInfo).then(flag => {
        if (flag) {
          apps.value.splice(index, 1);
        }
      });
      return;
    }
    const next = apps.value[index + 1];
    const prev = apps.value[index - 1];
    let activeData;
    if (next) {
      activeData = next;
    } else if (prev) {
      activeData = prev;
    } else {
      activeData = appInfo;
    }
    remoteApp(appInfo).then(flag => {
      if (!flag) {
        return;
      }
      apps.value.splice(index, 1);
      changeApp(activeData);
    });
  }

  function onContextmenu(e) {
    console.log(e);
  }

  let isClosing = false;

  function shouldCloseWindow() {
    if (isClosing) {
      return;
    }
    isClosing = true;
    Modal.confirm({
      title: '是否关闭当前应用窗口？',
      content:
        '如果您当前窗口中操作的数据还未保存，请先保存后再关闭，如果您不保存更改，您的更改将丢失。',
      onOk() {
        isClosing = false;
        return ipcRenderer.invoke('replyRenderer__workbenchApplicationWindow_shouldCloseWindow');
      },
      onCancel() {
        isClosing = false;
      },
    });
  }
</script>
